﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Leave;
using B.S.BasicData.Domain.Entities.Leave;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.Leave
{
    /// <summary>
    /// 创建我的申请请求命令处理类
    /// </summary>
    public class CreateMyLeaveHandler:IRequestHandler<CreateMyLeaveCommand,ApiResult<int>>
    {
        IBaseRepository<LeaveApplicationModel> leaveRep;
        IMapper mapper;

        public CreateMyLeaveHandler(IBaseRepository<LeaveApplicationModel> leaveRep, IMapper mapper)
        {
            this.leaveRep = leaveRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateMyLeaveCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var entity=mapper.Map<LeaveApplicationModel>(request);
                entity.State=LeaveStateEnum.待处理;
                entity.CreateDate = DateTime.Now;
                entity.CreateName=request.applicationName;

                int r=leaveRep.CreateAsync(entity).Result;
                if(r>0)
                {
                    res.Msg = "申请已提交";
                    res.Code=ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "申请提交失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
